package com.bdzl.ecs.util.file;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.bdzl.ecs.config.Constant;

import java.io.InputStream;
import java.util.*;

/**
 * 阿里云存储客户端实例工厂类
 *
 * @author chenjl
 */
public class OSSClientFactory {
    private OSSClientFactory() {
    }

    private static Map<String, OSSClient> clients = new HashMap<>();

    /**
     * 使用aliyun.properties中的配置获取一个实例
     *
     * @return
     */
    public static OSSClient getInstance() {
        String endpoint_sz = "oss-cn-hangzhou.aliyuncs.com";// 外网域名oss-cn-shenzhen.aliyuncs.com
        String accesskey = "LTAIb59vUeT2OABK";
        String accesskeysecret = "o2OqTi5RphmCv42U2H05GLdupXXMWE";
        return getInstance(endpoint_sz, accesskey, accesskeysecret);
    }

    /**
     * 根据参数获取实例，同样的参数获得的实例是同一个
     *
     * @param endpoint        节点URL
     * @param accessKeyId     访问OSS的Access Key ID
     * @param secretAccessKey 访问OSS的Secret Access Key
     * @return
     */
    public static OSSClient getInstance(String endpoint, String accessKeyId, String secretAccessKey) {
        StringBuffer sbr = new StringBuffer();
        sbr.append(endpoint).append(accessKeyId).append(secretAccessKey);

        synchronized (clients) {
            if (clients.get(sbr.toString()) == null) {
                OSSClient client = new OSSClient(endpoint, accessKeyId, secretAccessKey);
                clients.put(sbr.toString(), client);
                return client;
            }
            return clients.get(sbr.toString());
        }

    }

    /**
     * 上传到OSS服务器
     *
     * @author chenjl
     */
    public static PutObjectResult uploadFile(String path, InputStream input) throws OSSException, ClientException {
        return OSSClientFactory.getInstance().putObject(Constant.OSS_BUCKETNAME, path, input);
    }


    public static void remove(String url) {
        OSSClient client = OSSClientFactory.getInstance();
        client.deleteObject(Constant.OSS_BUCKETNAME, url.replace(Constant.OSS_PIC_PREFIX, ""));
    }

    public static void bathRemove(List<String> urls) {
        urls.removeAll(Collections.singleton(null));
        OSSClient client = OSSClientFactory.getInstance();
        DeleteObjectsRequest request = new DeleteObjectsRequest(Constant.OSS_BUCKETNAME);
        List<String> list = new ArrayList<>();
        for (String url : urls) {
            list.add(url.replace(Constant.OSS_PIC_PREFIX, ""));
        }
        request.setKeys(list);
        client.deleteObjects(request);
    }
}
